package br.ufc.cloud;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.*;
import br.ufc.cloud.*;

public class Search extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String name = req.getParameter("name").toLowerCase();

		List<Entity> users = searchUserByName(name);
		if (users != null && users.size() > 0) {
			for (Entity entity : users) {
				String address, email, phone;
				BlobKey photoBlobKey;

				address = (String) entity.getProperty("address");
				email = (String) entity.getProperty("email");
				phone = (String) entity.getProperty("phone");
				photoBlobKey = (BlobKey) entity.getProperty("photoBlobKey");
				long keyUser = entity.getKey().getId();
				
				resp.getWriter().print("<html>");
				resp.getWriter().print("<body>");
				resp.getWriter().print("<table border=\"3\">");

				ListarContatos listarContatos = new ListarContatos();
				listarContatos.WriteHtmlList(name, address, email, phone,
						photoBlobKey, resp, keyUser);

				resp.getWriter().print("</table>");

				resp.getWriter()
						.print("<input type=\"button\" value=\"Voltar\" onclick=\"history.go(-1)\"");
				resp.getWriter().print("</body>");
				resp.getWriter().print("</html>");

			}
		} else {
			resp.getWriter().print("Erro: Usu�rio n�o encontrado");
		}

	}

	public List<Entity> searchUserByName(String name) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Filter filterName = new FilterPredicate("name", FilterOperator.EQUAL,
				name);
		List<Entity> users = null;
		Query query = new Query("User").setFilter(filterName);
		PreparedQuery preparedQuery = datastore.prepare(query);
		users = preparedQuery.asList(FetchOptions.Builder.withDefaults());

		return users;
	}

}
